<template>
  <!-- 头部 -->
  <uni-nav-bar title="扫码加注" color="#333" left-icon="left" @clickLeft="redirectTo('index/filling')"
    statusBar></uni-nav-bar>
  <environment></environment>
  <image :src="BGicon2" class="state_img" v-if="orderAll.pin_id===0"></image>
  <scantopone v-else :orderInfo="orderInfo"></scantopone>
  <!-- 加注状态 -->
  <view class="state">
    <view v-if="fillingType.fill_status < 3">
      单号
      <text class="text">{{ orderNo }}</text>
      ,
      <text>请在{{ orderAll.code }}</text>
      上加注完成后刷新查看结果
    </view>
    <view style="font-size: 34rpx" v-if="fillingType.fill_status > 2">加注已完成{{ overOrder }}</view>
  </view>
  <!-- 加注信息 -->
  <view class="package" v-if="fillingType">
    <view class="space-between">
      <view style="font-size: 30rpx">订单号</view>
      <view>
        <text @click="copyText(orderAll.order_sn)" class="but">复制</text>
        <text>{{ orderAll.order_sn.substring(0, 16) }}</text>
        <text style="color: #1b91ff">{{ orderNo }}</text>
      </view>
    </view>
    <view class="space-between top">
      <text>加注方式</text>
      <text>{{ orderAll.type == 'quota' ? '定额' : '定量' }}</text>
    </view>
    <view class="space-between top">
      <text>加注量</text>
      <text>{{ orderAll.amount }}公斤</text>
    </view>
    <view class="space-between top" v-if="orderAll.order_type !== 'customers_filling'">
      <text>实付</text>
      <text>¥{{ orderAll.total_amount }}</text>
    </view>
    <view class="space-between top">
      <text>加注机</text>
      <text>{{ orderAll.fill_code }}</text>
    </view>
    <view class="space-between top">
      <text>消费者</text>
      <text>{{ orderAll.preparer }}</text>
    </view>
  </view>
  <!-- 加注信息 -->
  <view class="package" v-if="fillingType">
    <view class="space-between">
      <text>实际加注量</text>
      <text>{{ fillingType.fill_status != '0' ? fillingType.fill_amount + '公斤' : '**' }}</text>
    </view>
    <view class="space-between top">
      <text>消费金额</text>
      <text>{{ fillingType.fill_status != '0' ? '¥ ' + fillingType.fill_fee : '**' }}</text>
    </view>
    <view class="space-between top" v-if="orderAll.order_type !== 'customers_filling'">
      <text>退款金额</text>
      <text>{{ fillingType.fill_status != '0' ? '¥ ' + fillingType.tui_fee : '**' }}</text>
    </view>
    <view class="space-between top" v-if="orderAll.order_type !== 'customers_filling'">
      <text>积分</text>
      <text>{{ fillingType.fill_status != '0' ? fillingType.score : '**' }}</text>
    </view>
  </view>
  <view class="botTitle" v-if="Popup">
    <text>您还未绑定手机号，为了更好的提供服务</text>
    <text @click="openPhonePad()">请绑定手机号</text>
  </view>
  <view class="package" style="background: linear-gradient(212deg, #C0EEFC, #E8ECFA);">
    <view style="font-size: 60rpx;font-family: PangMenZhengDao-3;font-style: italic;color: #477BEF;">邀请新客拿奖励</view>
    <view class="space-between">
      <view>
        <view>快快前去参与吧！</view>
        <view class="invite" @click="navTo('invitation/invitation')">立即邀请</view>
      </view>
      <tki-qrcode ref="qrcode" cid="1" :val="val" />
    </view>
  </view>
  <!-- 手机号面板弹框 -->
  <uni-popup ref="PhonePadPopup" type="bottom" :is-mask-click="false" style="z-index: 910">
    <PhonePad type="bind" @close="closePhonePad" />
  </uni-popup>
  <!-- 关注公众号 -->
  <uni-popup ref="Verify" type="center">
    <view class="poupon">
      <view class="top_poupon">
        <image src="../../static/login/wecat.png" mode="" class="top_img"></image>
        <text>关注“安蓝车用尿素互联网整体解决方案”公众号</text>
      </view>
      <image src="../../static/login/we.png" mode="" class="poupon_img" :show-menu-by-longpress="true"></image>
      <view class="title_poupon">长按识别二维码</view>
    </view>
  </uni-popup>
  <!-- 福利品商城入口 -->
  <uni-popup ref="shopPopup" type="center" style="z-index: 910">
    <view class="package column" style="background: rgba(255,255,255,.8);width:600rpx;">
      <view style="margin-top:20rpx;">您现在有{{geamInfor.gem}}可兑换福利商品</view>
      <view class="come" @click="jump()">进入福利商城>></view>
    </view>
  </uni-popup>
  <webWechat :path="path" :title="text" ref="webWechats" v-if="text"></webWechat>
</template>

<script setup lang="ts">
  import tkiQrcode from "@c/tki-qrcode/tki-qrcode.vue"
  import { fillingOr, checkTanGem } from '@/gql/filling';
  import { getPinOrderInfo } from '@/gql/together';
  import { getDriverID } from '@/stores/driverID';
  import { copyText } from '@/utils/copyText';
  import { redirectTo, navTo } from '@/utils/navigator';
  import environment from '@c/pobulic/environment.vue';
  import scantopone from '@c/canCode/ScanTopOne.vue';
  import { showLoading } from '@/utils/prompt';
  import { onLoad, onPullDownRefresh, onShow, onUnload, } from '@dcloudio/uni-app';
  import { subject, subscribe, toPublish, unsubscribe } from '@mqtt';
  import { useUserStore } from '@/stores/user';
  import { BGicon2 } from '@/utils/Static';
  import PhonePad from '@c/common/PhonePad.vue';
  import type { Subscription } from 'rxjs';
  import { computed, Ref, ref } from 'vue';
  import webWechat from '@c/pobulic/webWechat.vue';
  /**
   * @component
   * @desc 提交订单成功页面
   * @property {Number} driver_id 用户ID
   * @property {String} userInfo 用户信息
   * @property {Number} order_id 用户订单ID
   * @property {Boolean} Popup 是否绑定手机号码弹框
   * @property {Null} Verify 关注公众号弹框值
   * @property {Object} orderAll 订单信息
   * @property {String} overOrder 加注完成提示语
   * @property {String} orderNo 订单后四位
   * @property {Null} subscription 存储已经启动过的流，其 unsubscribe 方法可以停止该流
   */
  const driver_id = getDriverID();
  const userInfo = useUserStore();
  // static
  let order_id = null as number; //订单ID
  const val = ref('')
  // refs
  const Popup = ref(false);
  const PhonePadPopup = ref(null);
  const shopPopup = ref(null)
  const webWechats = ref(null)
  const Verify = ref(null);
  const orderAll : Ref<any> = ref({ order_sn: '' }); //订单状态
  const fillingType : Ref<any> = ref({}); //加注状态
  const overOrder = ref(''); //已完成用语
  const orderInfo = ref()
  const orderNo = computed(() => orderAll.value.order_sn.slice(-4));
  // data
  let subscription : Subscription = null;
  const qrcode = ref(null)
  const path = ref('');
  const text = ref('');
  const innerAudioContext = ref(null)

  const geamInfor = ref()
  onLoad(({ id }) => {
    order_id = Number.parseInt(id);
    setTimeout(() => {
      qrcode.value._makeCode()
      if (!userInfo.mobile) {
        Popup.value = true
      } else if (uni.getStorageSync('storage_key').is_subscribe === '0') {
        Verify.value.open();
      }
    }, 1000)
    const time = Date.parse(new Date())
    val.value = `https://wx.anlan.tech/#/?type=yaoxin&zhitui_id=${driver_id}&key=${time}`;
    innerAudioContext.value = uni.createInnerAudioContext()
    tanGem()
  });

  onUnload(() => {
    innerAudioContext.value.pause()
    if (subscription !== null) {
      subscription.unsubscribe();
    }
    deltopics();
  });

  onShow(() => {
    userInfo.getUserInfo();
    // 获取页面信息
    scanCodes();
  });

  // 下拉刷新获取页面信息
  onPullDownRefresh(scanCodes);

  /**
   * 获取正在加注页面信息
   */
  function scanCodes() {
    showLoading('加载中');
    const payload = {
      query: fillingOr,
      variables: {
        driver_id,
        order_id,
      },
    };
    toPublish('ql/driver/doFillingOrder', payload, (obj : any) => {
      const { fill_order } = obj.data;
      // TODO
      orderAll.value = fill_order;
      fillingType.value = fill_order;
      overOrder.value = fill_order.goods && fill_order.fill_amount > 9.99 ? ',' + fill_order.goods : '';
      if (orderAll.value.pin_id !== 0) {
        collage(orderAll.value.pin_id)
        path.value = `https://wx.anlan.tech/#/?type=pinOrder&pin_id=${orderAll.value.pin_id}&driver_id=${driver_id}`
        text.value = userInfo.nickname + '邀请您参与拼单'
      }
      // 订阅主题
      topics();
    });
    uni.stopPullDownRefresh();
  }
  function tanGem() {
    showLoading('加载中');
    const payload = {
      query: checkTanGem,
      variables: {
        order_id,
      },
    };
    toPublish('ql/driver/checkTanGem', payload, (obj : any) => {
      const { checkTanGem } = obj.data;
      if (checkTanGem.gem) {
        geamInfor.value = checkTanGem
        innerAudioContext.value.loop = true;
        innerAudioContext.value.src = checkTanGem.mp3;
        innerAudioContext.value.autoplay = true;
        innerAudioContext.value.onPlay(() => {
          console.log('是否可以播放')
        })
        shopPopup.value.open()
      }
    });
  }
  function collage(id : number) {
    const payload = {
      query: getPinOrderInfo,
      variables: {
        driver_id,
        id,
      },
    };
    toPublish('ql/driver/getPinOrderInfo', payload, (obj : any) => {
      const { getPinOrderInfo } = obj.data;
      orderInfo.value = getPinOrderInfo
    });
  }
  /**
   * 订阅主题
   */
  function topics() {
    const token = driver_id;
    const topic = 'formal/v1/order/fill_status/client/' + token;
    toSubscribe();
    subscribe(topic);
  }
  /**
   * 取消订阅
   */
  function deltopics() {
    toUnsubscribe();
    const token = driver_id;
    const topic = 'formal/v1/order/fill_status/client/' + token;
    unsubscribe(topic);
  }

  function toSubscribe() {
    if (subscription === null) {
      subscription = subject.subscribe(scanCodes);
    }
  }

  function toUnsubscribe() {
    subscription.unsubscribe();
    subscription = null;
  }
  function openPhonePad() {
    PhonePadPopup.value.open();
  }
  function closePhonePad() {
    PhonePadPopup.value.close();
    Popup.value = false
  }
  function jump(){
    shopPopup.value.close()
    navTo('gemstone/shopList?type=free')
  }
</script>

<style lang="less">
  .come {
    width: 285rpx;
    height: 82rpx;
    background: linear-gradient(-66deg, #FF7B48, #FF5B45);
    border-radius: 41rpx;
    text-align: center;
    line-height: 82rpx;
    color: #fff;
    margin: 50rpx auto 20rpx;
  }

  @import url('../canCode/less/canState.less');
</style>